//
//  iOS28thStudensDBTool.m
//  what
//
//  Created by 飞奔的羊 on 16/4/25.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "iOS28thStudensDBTool.h"
#import "FMDB.h"

@implementation iOS28thStudensDBTool
FMDatabase *_db;

+ (void)initialize
{
    NSString *dbPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"ha.db"];
    //创建
    _db = [FMDatabase databaseWithPath:dbPath];
    //打开
    BOOL result = [_db open];
    if (result) {
        NSLog(@"创建成功");
        BOOL result1 = [_db executeUpdate:@"create table if not exists T_student(studentId integer parimary key,studentName text not null,studentAge integer default 18);"];
        
        if (result1) {
            NSLog(@"创建表成功");
        }
        
        
        
        
    }
    
    
    
    
    
}

+ (void)insertStudent:(iOS28thStudents *)students
{
    BOOL result = [_db executeUpdateWithFormat:@"insert into T_student(studentName,studentAge) values(%@,%d)",students.name,students.age];
    if (result) {
        NSLog(@"添加成 going");
    }

}

+ (void)updateStudent:(iOS28thStudents *)students
{
    BOOL result = [_db executeUpdateWithFormat:@"update T_student set studentAge = %d where studentName = %@",students.age,students.name];
    if (result) {
        NSLog(@"添加成 going");
    }


}

+ (void)deleteStudent:(iOS28thStudents *)students
{



    BOOL result =[_db executeUpdateWithFormat:@"delete from T_student where studentName=%@",students.name];
    
    if (result) {
        NSLog(@"删除成功!!!");
    }
}


+ (NSArray *)queryAll
{
    FMResultSet *resultSet = [_db executeQuery:@"select * from T_student;"];
    
    //遍历集合
    NSMutableArray *students = [NSMutableArray array];
    while ([resultSet next]) {
        NSString *name = [resultSet stringForColumn:@"studentName"];
        int age = [resultSet intForColumn:@"studentAge"];
        
        NSLog(@"%@---%d",name,age);
        
        iOS28thStudents *student = [[iOS28thStudents alloc] init];
        student.name = name;
        student.age =  age;
        
        [students addObject:student];
    }
    
    return students;


}
+ (NSArray *)queryWithKeyWord:(NSString *)keyWord
{
    FMResultSet *resultSet = [_db executeQuery:[NSString stringWithFormat:@" select * from T_student where studentName like '%%%@%%' ",keyWord]];
    
    //遍历我们结果集合
    NSMutableArray *students = [NSMutableArray array];
    while ([resultSet next]) {
        NSString *name = [resultSet stringForColumn:@"studentName"];
        int age = [resultSet intForColumn:@"studentAge"];
        
        NSLog(@"%@---%d",name,age);
        
        iOS28thStudents *student = [[iOS28thStudents alloc] init];
        student.name = name;
        student.age =  age;
        
        [students addObject:student];
    }
    
    return students;



}


@end
